package ch.mse.android.starbucksfinder;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import ch.mse.android.starbucksfinder.helper.DBHelper;
import ch.mse.android.starbucksfinder.helper.MessageHelper;
import ch.mse.android.starbucksfinder.net.ServerConnector;

public class StarterActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        registerListeners();
    }

	private void registerListeners() {
		Button downloadButton = (Button)findViewById(R.id.downloadButton);
		downloadButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(final View v) {
				final AlertDialog dlg = MessageHelper.displayModalMessage(v.getContext(), "Info", "Please wait while data is beeing downloaded.");
				new Thread(new Runnable() {
				    public void run() {
				    	ServerConnector connector = new ServerConnector();
				    	List<StarbucksLocation> storeList;
				    	try {
				    		storeList = connector.downloadAndParse();
				    		DBHelper dbhelper = new DBHelper(getApplicationContext());
				    		dbhelper.deleteAllLocations();
				    		for(StarbucksLocation l : storeList)
				    			dbhelper.addLocation(l);
				    	} catch (final Exception e) {
				    		v.post(new Runnable() {
								public void run() {
									dlg.hide();
									MessageHelper.displayAlertMessage(getApplicationContext(), "Error", "Couldn't download data.");
								}
							});
				    	}
				    	v.post(new Runnable() {public void run() {dlg.hide();}}); 
				    }
				}).start();
			}
		});
		
		Button locateButton = (Button)findViewById(R.id.locateButton);
        locateButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent myIntent = new Intent(v.getContext(), MapActivity.class);
                startActivity(myIntent);
			}
		});
	}
	
}